from sysmanage.models import User, Online
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponseRedirect
from django.contrib.auth.hashers import make_password
from django.contrib.auth import logout  # 退出session
from loginmanage.util import *  # 自定义工具类
import uuid


# 登陆
@csrf_exempt
def login(request):
    path = request.scheme + "://" + request.get_host()  # url
    ff_path = request.scheme + "://" + request.get_host() + request.path  # 加方法url
    if request.method == 'GET':  # 如果是get请求
        quit(request)  # 只要登录页面，清除以前用户session
        return render(request, 'login/login.html', {'path': path, 'ff_path': ff_path})  # 交给前台
    else:
        username = request.POST.get("username")  # 获取前台post 提交的username
        password = request.POST.get("password")  # 获取前台post 提交的password
        # 查询用户是否存在
        try:
            db_username = User.objects.get(username=username)
        except User.DoesNotExist as e:
            return redirect('/login')

        # 如果存在,验证密码是否正确
        if password != db_username.password:
            return redirect('/login')

        request.session.set_expiry(1000)
        response = HttpResponseRedirect('index')
        token = make_password(username)
        db_username.token = token
        db_username.save()
        response.set_cookie('userToken', token)
        request.session['username'] = db_username.username  # 给session放入username字段
        response.set_cookie('usernameKey', 'username')
        response.set_cookie('user_id', db_username.user_id)  # 给session放入userid字段
        response.set_cookie('user_full_name', db_username.user_full_name)  # 给session放入user_full_name字段
        response.set_cookie('username', db_username.username)  # 给session放入username字段
        response.set_cookie('role_id', db_username.role_id)  # 给session放入role_id字段
        Online.objects.create(user_id=db_username.user_id)  # 给上线表插入数据
        return response


# 退出方法
@csrf_exempt
def quit(request):
    if check_session(request):
        user_id = request.COOKIES.get('user_id')
        Online.objects.filter(user_id=user_id).delete()  # 删除当前用户上线记录
        logout(request)
        return redirect('/index')
    else:
        response = HttpResponseRedirect('/login')
        return response
